var tableElem = "LAY-home-faq-list";
var tableToolsElem = "LAY-home-faq-tools";
var formElem = "LAY-home-faq-listform";
var formSubmitElem = "LAY-home-faq-listform-submit";
var formUrl = '/home/faq/listform'
var historyUrl = '/home/faq/list'
var baseUrl = window.globalConfig.url_faq


layui.use(['common'], function (common) {
    var $ = layui.$
        , admin = layui.admin
        , table = layui.table
        , form = layui.form

    /**
     * 主页面管理
     */
    var tableItem = table.render({
        elem: `#${tableElem}`
        , lineStyle: 'height: 80px;'
        , url: baseUrl
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'id', title: '问答id', sort: true}
            , {
                field: 'faqCategory_name',
                title: '问答分类',
                minWidth: 200,
                templet: "#TPL-dropdown-faqCategory"
            }
            , {field: 'question', title: '问题', minWidth: 200, edit: 'text'}
            // , {field: 'redirect_link', title: '跳转链接', minWidth: 350, edit: 'text'}
            // , {field: 'answer', title: '答案', maxWidth: 150, edit: 'text'}
            , {field: 'sort', title: '排序', edit: 'text'}
            , {title: '操作', minWidth: 220, align: 'center', fixed: 'right', toolbar: `#${tableToolsElem}`}
        ]]
        , text: {none: '暂无数据！'}
        , done(d) {
            let faqs = d.data
            for (let i = 0; i < faqs.length; i++) {
                admin.req({
                    url: window.globalConfig.url_faqCategory + "/" + faqs[i].cat_id,
                    method: 'GET',
                    done(res) {
                        faqs[i].cat_name = res.data.name;
                        $(`.cat_name_${faqs[i].id}`).text(res.data.name);
                    }
                })

            }
            common.tableDropdownEditor(this, window.globalConfig.url_faqCategory, baseUrl, 'id', 'cat_id')
        }
    });

    var active = {
        //添加
        add: function (othis) {
            location.hash = `${formUrl}`;
        }
    };

    $('.layui-btn.layuiadmin-btn-list').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    // 增删改查
    table.on(`tool(${tableElem})`, function (obj) {
        var data = obj.data;
        if (obj.event === "detail") {  // 查看详情


        } else if (obj.event === 'del') { // 删除详情
            layer.confirm('确定删除此问答？', function (index) {
                admin.req({
                    url: baseUrl + "/" + data.id,
                    type: "DELETE",
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        layer.close(index);
                        tableItem.reloadData(); //重载表格
                    }
                })
            });
        } else if (obj.event === 'edit') {// 修改详情
            location.hash = `${formUrl}/id=` + data.id;
        }
    });

    // 表单模块
    layui.data.done = function (d) {
        var remoteData = d.data
        layui.use(['form'], function () {

            form.render(null, formElem); //渲染该模板下的动态表单
            if (remoteData.cat_id) {
                admin.req({
                    url: window.globalConfig.url_faqCategory + "/" + remoteData.cat_id,
                    method: "GET",
                    done(d) {
                        $("#catName").val(d.data.name);
                    }
                })
            }

            // 加载编辑器
            let editors = {
                'answer-editor': 'answer',
            }
            common.loadEditors(remoteData,editors)


            // 加载下拉列表
            common.formDropdownEditor(
                `${window.globalConfig.url_faqCategory}?all=1`,
                "catName",
                "catId",
                "catName",
                "id",
                'name'
            )


            let dropdown = layui.dropdown;
            admin.req({
                url: window.globalConfig.url_cms_list + "?all=1",
                type: 'get',
                dataType: 'json',
                success: function (response) {
                    var data = response.data;
                    dropdown.render({
                        clickScope: 'all', elem: `#redirect_link`, data: data, click(data, othis) {
                            $(`#redirect_link`).val(window.globalConfig.base_domain + '/' + data['urlrewriter'])
                        }
                    });
                }
            });


            // 表单提交
            form.on(`submit(${formSubmitElem})`, function (data) {
                var field = data.field; //获取提交的字段
                field.is_best = field.is_best === undefined ? 0 : 1;
                field.is_top = field.is_top === undefined ? 0 : 1;
                field.is_hot = field.is_hot === undefined ? 0 : 1;

                field = common.getEditorsContent(field,editors)

                let url = baseUrl
                let type = "POST";
                if (remoteData.id) {
                    url += "/" + remoteData.id;
                    type = "PUT"
                }
                //提交 Ajax 成功后，关闭当前弹层并重载表格
                admin.req({
                    url: url,
                    type: type,
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        if (res.code === 0) {
                            setTimeout(() => {
                                history.back()
                            }, 1000)
                        }
                    }
                })

            });
        });
    };

    // 表格文本修改
    common.tableTextEditor(tableElem, baseUrl, 'id')
    common.tableSwitchEditor('faq-is_best-status', baseUrl)
    common.tableSwitchEditor('faq-is_top-status', baseUrl)
    common.tableSwitchEditor('faq-is_hot-status', baseUrl)
})